package org.box.metadata.shell.web.server;

import org.box.metadata.shell.WebShellDefaultConfiguration;
import org.box.metadata.shell.web.WebShell;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.session.HashSessionIdManager;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

public class NativeServer extends Server {

	private final WebShellDefaultConfiguration cfg;
	private final WebShell webShell;

	public NativeServer(WebShellDefaultConfiguration cfg, WebShell webShell) {
		super(cfg.getPort());
		this.cfg = cfg;
		this.webShell = webShell;
	}

	@Override
	protected void doStart() throws Exception {
		
		WebAppContext context = new WebAppContext();
		if (cfg.getResourceBase() != null) {
			context.setResourceBase(cfg.getResourceBase());
		} else {
			context.setWar(cfg.getWarFile());
		}
		
		ServletContextHandler scHandler = new
	            ServletContextHandler(ServletContextHandler.SESSIONS);
		
		scHandler.setContextPath("/");
		scHandler.addServlet(createWSCfgServlet(), "/ws/*");
		
		HandlerCollection collection = new HandlerCollection();
		collection.addHandler(scHandler);
		collection.addHandler(context);
		
		setHandler(collection);
		setSessionIdManager(new HashSessionIdManager());

		super.doStart();
		scHandler.getServletContext().setAttribute(WebShell.SERVLET_CONTEXT_SHELL_ATTRIBUTE, webShell); 
	}
	
	public ServletHolder createWSCfgServlet() {
		ServletHolder holder = new ServletHolder(
					new com.sun.jersey.spi.container.servlet.ServletContainer());
		
		holder.setInitOrder(1);
		holder.setInitParameter(
				"com.sun.jersey.api.json.POJOMappingFeature", 
				"true");

		switch (cfg.getCSP()) {
		case CONCURRENT_SESSIONS:
			holder.setInitParameter(
					"com.sun.jersey.config.property.packages", 
					"org.box.metadata.shell.web.ws.cs");
			return holder;
		case GLOBAL_SESSION:
			holder.setInitParameter(
					"com.sun.jersey.config.property.packages", 
					"org.box.metadata.shell.web.ws.gs");

			return holder;
		case REJECT_NEW_SESSION:
			return null;
		}
		
		throw new IllegalStateException();
	}

}
